<template>
  <div class="app-container">
    <u-page title="返券记录">
      <u-filtered>
        <el-form :inline="true" class="search-form">
          <el-form-item label="订单号" prop="saleNo">
            <el-input v-model="saleNo" placeholder="请输入订单号" clearable style="width: 200px" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="checkOrder">核验小票是否已返券</el-button><span style="margin-left:10px;color: red;font-size:10px;">(已返券的小票不能进行退货操作)</span>
          </el-form-item>
        </el-form>
        <el-form :inline="true" :model="listQuery" class="search-form">
          <el-form-item label="档期主题" prop="scheduleId">
            <Schedule v-model="listQuery.schedule" width="160px" @change="changeScheduleQuery" />
          </el-form-item>
          <el-form-item label="返券时间" prop="daterange">
            <el-date-picker
              v-model="daterange"
              type="daterange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
          <el-form-item label="订单号" prop="saleNo">
            <el-input v-model="listQuery.saleNo" placeholder="请输入订单号" clearable style="width: 170px" />
          </el-form-item>
          <el-form-item label="会员卡号" prop="card_no">
            <el-input v-model="listQuery.card_no" placeholder="请输入会员卡号" clearable style="width: 170px" />
          </el-form-item>
          <el-form-item label="顾客编号" prop="custno">
            <el-input v-model="listQuery.custno" placeholder="请输入顾客编号" clearable style="width: 170px" />
          </el-form-item>
          <el-form-item label="终端类型" prop="type">
            <el-select v-model="listQuery.approachType" placeholder="请选择类型" class="disabled" clearable>
              <el-option v-for="item in approachTypeList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="queryMainnote">搜索</el-button>
            <el-button type="primary" icon="el-icon-download" @click="handleDownload">导出</el-button>
          </el-form-item>
        </el-form>
      </u-filtered>
      <u-table
        :data="list"
        :loading="listLoading"
        :options="listOptions"
        :columns="columns"
        :pagination.sync="listQuery"
        :fetch="queryMainnote"
        @selection-change="hdlSelectChange"
      >
        <template v-slot:right>
          <el-table-column label="操作" align="center" fixed="right">
            <template slot-scope="{ row }">
              <el-button v-if="row.cardno.length>0" type="text" @click="queryDetails(row.custno,row.type)">查看</el-button>
              <el-button v-else type="text" @click="cancelRebate(row.custno)">撤销</el-button>
            </template>
          </el-table-column>
        </template>
      </u-table>
    </u-page>
    <!-- 返券明细 累计返券-->
    <u-dialog title="返券明细" :show.sync="showLJFQ" width="760px" :auto-close="false" :footer="false" @cancel="cancel">
      <div style="padding:10px 5px; margin-bottom:10px;background-color: #e7faf0;color: #13ce66;"><span style="margin-right: 40px;">券号：{{ mainInfo.couponNo }}</span><span>发券流水：{{ mainInfo.tranNo }}</span></div>
      <div v-for="(item,index) in itemList" :key="index">
        <div>
          <div class="log-item-title">
            <div style="width:300px;margin-right: 10px;">【{{ item.rebateOperation.name }}】</div>
            <div style="width:300px;margin-right: 10px;">返券金额：{{ item.amount }}</div>
            <div v-if="item.status===1" style="width:100px;"><el-button style="font-size: 16px;" type="text" @click="refundLJFQ(item)">退券</el-button></div>
            <!--<span v-if="item.status===1" style="width:60px;"><el-button style="color:red;" type="text" @click="abnormalfund(item)">异常退券</el-button></span>-->
          </div>
          <div v-for="(order,oIndex) in item.orderList" :key="oIndex">
            <div class="log-item">
              <div style="width:250px;margin-right: 10px;">订单号：{{ order.saleNo }}</div>
              <div style="width:150px;margin-right: 10px;">订单金额：{{ order.saleAmount }}</div>
              <div style="width:150px;margin-right: 10px;">有效金额：{{ order.validAmount }}</div>
              <div v-if="order.status===2" style="width:100px;color:red;">（已退券）</div>
            </div>
          </div>
        </div>
      </div>
    </u-dialog>
    <!-- 返券明细 单笔返券/累计多级满赠/单笔多级满赠-->
    <u-dialog title="返券明细" :show.sync="showDBFQ" width="760px" :auto-close="false" :footer="false" @cancel="cancel">
      <div style="padding:10px; margin-bottom:10px;background-color: #e7faf0;color: #13ce66; display: flex;">
        <span style="margin-right: 40px;"> 活动名称：{{ DBFQdetails.operationCoupon.name }}</span>
        <span>消费门槛：{{ DBFQdetails.operationCoupon.threshold }}</span>
      </div>
      <div class="log-item-title">发券明细</div>
      <div v-for="(item,index) in DBFQdetails.couponList" :key="index" style="margin-bottom: 20px;">
        <div class="log-item">
          <div style="width:240px;margin-right: 10px;">券名：{{ item.couponName }}</div>
          <div style="width:240px;margin-right: 10px;">券号：{{ item.couponNo }}</div>
          <div style="width:250px;margin-right: 10px;">发券流水：{{ item.tranNo }}</div>
        </div>
      </div>
      <div v-if="DBFQdetails.orderList">
        <div class="log-item-title">小票明细</div>
        <div v-for="(item,index) in DBFQdetails.orderList" :key="index" style="margin-bottom: 20px;">
          <div class="log-item">
            <div style="width:250px;margin-right: 10px;">订单号：{{ item.saleNo }}</div>
            <div style="width:150px;margin-right: 10px;">订单金额：{{ item.saleAmount }}</div>
            <div style="width:150px;margin-right: 10px;">有效金额：{{ item.validAmount }}</div>
          </div>
        </div>
      </div>
      <div style="text-align: center;">
        <el-button v-if="DBFQdetails.mainNote.status===1" style="font-size: 16px;" type="text" @click="refundDBFQ(item)">一键退券</el-button>
        <div v-else style="color:red;">（已退券）</div>
      </div>
    </u-dialog>
  </div>
</template>

<script>
import Schedule from '../components/schedule'
export default {
  components: {
    Schedule
  },
  data() {
    return {
      api: this.$u.api.RebatenewCouponlog,
      apiRefund: this.$u.api.RebatenewRefund,
      apiRebate: this.$u.api.RebatenewRebatecoupon,
      saleNo: '', // 核验小票
      daterange: [], // 返券时间
      showLJFQ: false,
      showDBFQ: false,
      DBFQdetails: {
        'title': '',
        'couponlist': [],
        'order': {},
        'mainNote': {},
        'operationCoupon': {}
      },
      listQuery: {
        page: 1,
        pageSize: 10,
        totalCount: 1,
        custno: '',
        saleNo: '',
        card_no: ''
      },
      approachTypeList: [
        {
          value: '',
          label: '全部'
        },
        {
          value: '1',
          label: 'CSMS后台'
        }, {
          value: '2',
          label: '小程序'
        }
      ],
      // 表格
      columns: [
        {
          prop: 'name',
          label: '档期主题'
        },
        {
          prop: 'type',
          label: '活动类型',
          render: (h, params) => {
            if (params.row.type === 1) {
              return h('el-tag', { props: { type: 'success' }}, '累计返券')
            } else if (params.row.type === 2) {
              return h('el-tag', '单笔多级满赠')
            } else if (params.row.type === 3) {
              return h('el-tag', { props: { type: 'danger' }}, '累计多级满赠')
            } else if (params.row.type === 5) {
              return h('el-tag', { props: { type: 'warning' }}, '单笔返券')
            } else if (params.row.type === 6) {
              return h('el-tag', { props: { type: 'success' }}, '满额返券')
            }
          }
        },
        {
          prop: 'custno',
          label: '顾客编号'
        },
        {
          prop: 'cardno',
          label: '会员卡号'
        },
        {
          prop: 'cardno_other',
          label: '代领人'
        },
        {
          prop: 'sumvalidamount',
          label: '返券金额'
        },
        {
          prop: 'couponcount',
          label: '返券张(套)数'
        },
        {
          prop: 'approachtype',
          label: '终端类型',
          render: (h, params) => {
            if (params.row.approachtype === 1) {
              return h('el-tag', { props: { type: 'success' }}, 'CSMS后台')
            } else {
              return h('el-tag', '小程序')
            }
          }
        },
        {
          prop: 'status',
          label: '状态',
          render: (h, params) => {
            if (params.row.status === 1) {
              return h('el-tag', { props: { type: 'success' }}, '已返券')
            } else if (params.row.status === 3) {
              return h('el-tag', '未返券')
            } else if (params.row.status === 2) {
              return h('el-tag', { props: { type: 'danger' }}, '已退券')
            } else {
              return h('el-tag', { props: { type: 'warning' }}, '部分退券')
            }
          }
        },
        {
          prop: 'createdby',
          label: '操作人'
        },
        {
          prop: 'createdat',
          label: '返券时间',
          sortable: true,
          timestamp: true
        }
      ],
      listLoading: false,
      list: [],
      listOptions: {
        stripe: true
      },
      mainInfo: {},
      itemList: []
    }
  },
  created() {
    // this.queryMainnote()
  },
  methods: {
    changeScheduleQuery(item) {
      this.listQuery.scheduleId = item.id
    },
    //  查询主记录
    queryMainnote() {
      this.dateFormat()
      const self = this
      // 打开加载状态
      self.listLoading = true
      if (self.listState) {
        // 查询列表数据
        self.api.rebateNotes(self.listQuery).then(res => {
          // 获取列表数据
          self.list = res.data
          // 关闭加载状态
          setTimeout(() => {
            self.listLoading = false
          }, 0.5 * 1000)
        })
      } else {
        // 查询分页数据
        self.api.rebateNotes(self.listQuery).then(res => {
          // 获取分页列表数据
          self.list = res.data.list
          // 获取分页数据,总页数
          self.listQuery.totalCount = res.data.totalCount
          // 关闭加载状态
          setTimeout(() => {
            self.listLoading = false
          }, 0.5 * 1000)
        })
      }
    },
    // 关闭或者取消
    cancel() {
      this.showLJFQ = false
      this.showDBFQ = false
    },
    // 退券(累计返券)
    refundLJFQ(item) {
      const self = this
      // 模态对话框组件
      self.$confirm('将进行退券操作，是否继续？', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => {
        self.apiRefund.refundCouponLJFQ({
          'id': item.id,
          'amount': item.amount,
          'couponNo': item.couponNo
        }).then(res => {
          // 获取列表数据
          if (res.data === '退券成功') {
            self.$u.msg('退券成功！')
            self.showLJFQ = false
            self.showDBFQ = false
            self.queryDetails(item.custno, 1)
            self.queryMainnote()
          } else if (res.data === '退券失败') {
            self.$message.error('退券失败')
          } else {
            self.showLJFQ = false
            self.showDBFQ = false
            self.$message.warning('退券成功，退券状态更新失败')
          }
        })
      })
    },
    // 退券 （单笔返券/单笔多级满赠/累计多级满赠）
    refundDBFQ() {
      const self = this
      // 模态对话框组件
      self.$confirm('将进行退券操作，是否继续？', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => {
        self.apiRefund.refundCoupon({
          'id': self.DBFQdetails.mainNote.id,
          'couponList': self.DBFQdetails.couponList
        }).then(res => {
          // 获取列表数据
          if (res.data === '退券成功') {
            self.$u.msg('退券成功！')
            self.showLJFQ = false
            self.showDBFQ = false
            self.queryDetails(self.DBFQdetails.mainNote.custno, 5)
            self.queryMainnote()
          } else if (res.data === '退券失败') {
            self.$message.error('退券失败')
          } else {
            self.showLJFQ = false
            self.showDBFQ = false
            self.$message.warning('退券成功，退券状态更新失败')
          }
        })
      })
    },
    // 撤销操作
    cancelRebate(custno) {
      this.apiRebate.updateFailStatus({
        'custno': custno
      }).then(res => {
        console.log(res)
        this.queryMainnote()
      })
    },
    // 核验小票
    checkOrder() {
      const saleNo = this.saleNo
      if (saleNo === '') {
        return
      }
      console.log()
      this.api.checkOrder({
        'saleNo': saleNo
      }).then(res => {
        const h = this.$createElement
        if (res.data.flag) {
          var schedule = '该小票已参与'
          for (var i = 0; i < res.data.schedules.length; i++) {
            schedule += '【' + res.data.schedules[i] + '】'
          }
          schedule += '活动，禁止退货操作！'
          this.$msgbox({
            title: '已返券',
            message: h('span', { style: 'color: red' }, schedule),
            confirmButtonText: '确定'
          })
        } else {
          this.$msgbox({
            title: '未返券',
            message: h('span', { style: 'color: green' }, '该小票未返券,可以进行退货操作'),
            confirmButtonText: '确定'
          })
        }
        // 获取列表数据
        console.log(res)
      })
    },

    // 通过顾客编号查询明细
    queryDetails(custno, type) {
      // 累计返券1 其他
      if (type === 1) {
        this.showLJFQ = true
        this.api.orderNotesLJFQ({
          'custno': custno
        }).then(res => {
          // 获取列表数据
          this.itemList = res.data.itemlist
          this.mainInfo = res.data.mainInfo
          console.log(res)
        })
      } else {
        this.showDBFQ = true
        this.api.orderNotesDBFQ({
          'custno': custno
        }).then(res => {
          // 获取列表数据
          console.log(res.data)
          this.DBFQdetails = res.data
          console.log(this.DBFQdetails)
        })
      }
    },
    dateFormat() {
      if (this.daterange) {
        this.listQuery.startdate = this.daterange[0]
        this.listQuery.enddate = this.daterange[1]
      } else {
        this.daterange = []
        this.listQuery.startdate = ''
        this.listQuery.enddate = ''
      }
    },
    // 导出数据
    handleDownload() {
      // 复制值
      const list = this.$u.deepClone(this.list)
      // 业务数据处理
      list.forEach(item => {
        this.$set(item, 'approachtype', item.approachtype === 1 ? 'CSMS后台' : item.approachtype === 2 ? '小程序' : '')
        this.$set(item, 'status', item.status === 3 ? '未返券' : item.status === 1 ? '已返券' : item.status === 2 ? '已退券' : '部分退券')
        this.$set(item, 'type', item.type === 1 ? '累计返券' : item.type === 2 ? '单笔多级满赠' : item.type === 3 ? '累计多级满赠' : item.type === 5 ? '单笔返券' : item.type === 6 ? '满额返券' : '')
        this.$set(item, 'createdat', item.createdat ? this.$u.timeFormat(item.createdat) : '')
      })
      console.log(list)
      // 表头&表数据
      const tHeader = ['档期主题', '活动类型', '顾客编号', '会员卡号', '代领人', '返券金额', '返券张(套)数', '终端类型', '状态', '操作人', '返券时间']
      const filterVal = ['name', 'type', 'custno', 'cardno', 'cardno_other', 'sumvalidamount', 'couponcount', 'approachtype', 'status', 'createdby', 'createdat']
      const data = list.map(v => filterVal.map(j => { return v[j] }))
      this.$u.exports.excel('返券记录', tHeader, data)
    }
  }
}
</script>

<style lang="scss" scoped>
.log-item-title{
  font-size: 26px;
  border-top:2px solid #f1f1f1;
  border-bottom:2px solid #f1f1f1;
  padding:20px 10px;
  display: flex;
  background-color: #F4F5F9;
}
.log-item{
  padding:20px 40px;
  border-bottom:1px solid #f8f8f8;
  display: flex;
}
</style>
